package controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import view.Servidor;

public class ProcessaCliente
{

  private Socket client;
  private BufferedReader in;
  private PrintWriter out;

  private static int NUMERO_PROCESSO = 0;

  public ProcessaCliente(Socket client)
  {
    this.client = client;
  }

  public void processa()
  {
    Connection connection = null;
    ResultSet result = null;
    
    try
    {
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);

      String query = "SELECT * FROM carros WHERE id = ?;";

      ServidorSocket.semaforo().acquire();
      try
      {
        connection = getConnection();
      }
      catch (Exception e)
      {
        Servidor.mensagemErro("Problema ao abrir conexao com o banco.");
        e.printStackTrace();
        return;
      }

      String line = in.readLine();
      // semaforo.acquire();
      if (line != null)
      {
        PreparedStatement ps = connection.prepareStatement(query);
        ps.setInt(1, Integer.parseInt(line));

        Servidor.mensagemInformacao("Aguardando vez do processo " + Thread.currentThread().getName());
        //ServidorSocket.semaforo().acquire();
        Servidor.mensagemInformacao("Processsando:" + Thread.currentThread().getName());

        result = ps.executeQuery();
        Thread.sleep(5000);

        //ServidorSocket.semaforo().release();
        Servidor.mensagemInformacao("Fim do processo " + Thread.currentThread().getName());

        String mensagemRetorno = "";

        if (result.next())
        {
          String carro = "";
          for (int i = 1; i <= 10; i++)
          {
            mensagemRetorno += result.getString(i) + "#";
            if (i == 2)
            {
              SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
              Servidor.mensagemInformacao("Buscando informações do carro de placa " + result.getString(i) + " (" + sdf.format(new Date()) + ")");
            }

            if (i == 3 || i == 5)
            {
              carro += result.getString(i) + " ";
            }
          }
          Servidor.mensagemSucesso("Dados do carro encontrados! " + carro);
          out.println(mensagemRetorno);
        }/*
         * else {
         * Servidor.mensagemErro("Nenhum carro encontrado com essa placa."); }
         */
      }

      /*in.close();
      out.close();
      client.close();
      connection.close();
      result.close();*/

      
      
    }
    catch (Exception e)
    {
      Servidor.mensagemErro("Erro: " + e.getMessage());
      e.printStackTrace();    }
    finally {
      try {
        in.close();
        out.close();
        client.close();
        connection.close();
        result.close();
        
        Servidor.mensagemInformacao("Socket DOWN!");
        
      } catch (Exception e) {
        Servidor.mensagemErro("erro  " + e.getMessage());
      }
    }
    ServidorSocket.semaforo().release();
  }

  public Connection getConnection() throws ClassNotFoundException, SQLException{
    
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://187.45.196.134/malandronina5", "malandronina5", "so0902");
    //Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/placas", "root", "");
    return connection;
  }
  

  public void processaAssincrono(){
    
    new Thread(new ProcessadorAssincronoRunnable(), "Processador-"+NUMERO_PROCESSO++).start();
  }

  public class ProcessadorAssincronoRunnable implements Runnable {
    public void run(){
      processa();
    }
  }

}